package com.hk.core.data.r2dbc.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.domain.Persistable;
import org.springframework.util.ClassUtils;

import java.io.Serializable;
import java.util.Objects;

/**
 * @author Kevin
 */
@Setter
@Getter
public abstract class AbstractSnowflakeIdPersistable implements Persistable<Long>, Serializable {

    @Id
    private Long id;

    @Override
    @Transient
    @JsonIgnore
    public boolean isNew() {
        return null == getId();
    }

    @Override
    public String toString() {
        return String.format("Entity of type %s with id: %s", this.getClass().getName(), getId());
    }

    @Override
    public boolean equals(Object other) {
        if (Objects.isNull(other)) {
            return false;
        }
        if (this == other) {
            return true;
        }
        if (!getClass().equals(ClassUtils.getUserClass(other))) {
            return false;
        }
        var that = (AbstractSnowflakeIdPersistable) other;
        Long thisId = getId();
        return Objects.nonNull(thisId) && thisId.equals(that.getId());
    }

    @Override
    public int hashCode() {
        var hashCode = 17;
        Long thisId = getId();
        hashCode += Objects.isNull(thisId) ? 0 : thisId.hashCode() * 31;
        return hashCode;
    }
}
